package com.project.controller;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.project.model.entity.ProjectReport;
import com.project.service.ExportService;
import com.project.service.ProjectReportService;
import io.minio.*;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import io.minio.MinioClient;

import java.io.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import static com.project.model.constant.Minio.*;

@RestController
@RequestMapping("/export")
public class ExportController{

    @Autowired
    private ExportService exportService;

    @Autowired
    private ProjectReportService projectReportService;

    @GetMapping("/word")
    public void exportWord(@RequestParam("reportId") String reportId, HttpServletResponse response){
        System.out.println("导出的报告编码：" + reportId);
        try {

            XWPFDocument document = exportService.exportReportDateWord(reportId);

            //添加一个上传到Minio功能
            System.out.println("上传");
            upload(document,reportId);



            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition",
                    "attachment;filename=Report_" + System.currentTimeMillis() + ".docx");
            OutputStream os = response.getOutputStream();
            document.write(os);
            os.close();
/*            ServletOutputStream out = response.getOutputStream();
            document.write(out);
            out.close();
            document.close();*/


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @GetMapping("/pdf")
    public void exportPdf(@RequestParam("reportId") String reportId,HttpServletResponse response){
        try {
            // 获取 Word 文档
            XWPFDocument document = exportService.exportReportDateWord(reportId);

            // 设置响应内容类型为 PDF
            response.setContentType("application/pdf");
            response.setHeader("Content-disposition", "attachment;filename=Report_" + System.currentTimeMillis() + ".pdf");

            // 创建输出流
            OutputStream os = response.getOutputStream();

            // 创建 iText PDF 文档
            Document pdfDocument = new Document();
            PdfWriter.getInstance(pdfDocument, os);
            pdfDocument.open();

            // 将 Word 文档内容逐步转换为 PDF
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                // 每个段落转换为 iText 的 Chunk
                for (XWPFRun run : paragraph.getRuns()) {
                    Chunk chunk = new Chunk(run.text());
                    // 这里你可以设置更多的样式（如字体、大小等）
                    pdfDocument.add(chunk);
                }
                pdfDocument.add(Chunk.NEWLINE); // 添加换行
            }

            // 关闭文档和流
            pdfDocument.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void upload(XWPFDocument document,String id){
        try {
            // 创建 MinIO 客户端
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(MINIO_IP) // 替换为 MinIO 服务器 URL
                    .credentials(MINIO_ACCOUNT, MINIO_PASSWORD)
                    .build();


            // 将 XWPFDocument 写入 ByteArrayOutputStream
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            document.write(byteArrayOutputStream);

            // 将 ByteArrayOutputStream 转换为 InputStream
            byte[] documentBytes = byteArrayOutputStream.toByteArray();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(documentBytes);

            // 上传到 MinIO
            String bucketName = BUCKET_NAME;
            String objectName = "Report_" + System.currentTimeMillis() + ".docx";

            String reportUrl = MINIO_IP + BUCKET_NAME +"/"+ objectName;
            //写入对应的Report_url
            ProjectReport projectReport = projectReportService.getProjectReportById(Integer.valueOf(id));
            projectReport.setReportUrl(reportUrl);
            projectReportService.updateProjectReport(projectReport);

            // 检查存储桶是否存在
            BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
            if (!minioClient.bucketExists(bucketExistsArgs)) {
                // 使用 MakeBucketArgs 创建存储桶
                MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(bucketName).build();
                minioClient.makeBucket(makeBucketArgs);
            }

            // 上传文件
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .stream(inputStream, documentBytes.length, -1)
                            .contentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                            .build()
            );

            System.out.println("文件上传成功到 MinIO：" + objectName);
            inputStream.close(); // 关闭输入流以释放资源

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("上传文件到 MinIO 时出错：" + e.getMessage());
        }
    }

}
